package cn.wolfcode.wolf2w.business.service.impl;

import cn.wolfcode.wolf2w.business.api.RemoteStrategyService;
import cn.wolfcode.wolf2w.business.api.domain.Strategy;
import cn.wolfcode.wolf2w.business.api.domain.StrategyEs;
import cn.wolfcode.wolf2w.business.repository.StrategyEsRepository;
import cn.wolfcode.wolf2w.business.service.IStrategyEsService;
import cn.wolfcode.wolf2w.common.core.constant.SecurityConstants;
import com.alibaba.fastjson.JSON;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.stereotype.Service;

import javax.json.Json;
import java.util.ArrayList;
import java.util.List;

@Service
public class StrategyEsServiceImpl implements IStrategyEsService {
    @Autowired
    private RemoteStrategyService remoteStrategyService;

    @Autowired
    private StrategyEsRepository strategyEsRepository;

    @Override
    public void initStrategyEs() {
        //返回所有攻略的数组
        List<Strategy> list= remoteStrategyService.list(SecurityConstants.INNER).getData();
        List<StrategyEs> esList = new ArrayList<>();

        for (Strategy strategy : list) {
            StrategyEs es = new StrategyEs();
            //同名属性用拷贝,第一个参数：源头，第二个：目的
            BeanUtils.copyProperties(strategy,es);
            esList.add(es);
        }
        strategyEsRepository.saveAll(esList);
    }

    @RabbitListener(queues = {"strategyQueue"})
    public void onMessageReceive(String message){
        //改变类型
        Strategy strategy = JSON.parseObject(message, Strategy.class);
        //存储到es中，使用es类型
        StrategyEs es = new StrategyEs();
        BeanUtils.copyProperties(strategy,es);
        strategyEsRepository.save(es);
    }


}